package com.example.function.integration.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Description：CMD自动启动redis服务工具类
 * @Author： fengcheng
 * @Date： 2024/11/8 10:25
 */
public class CmdAutoStartRedisUtils {

    /**
     * @Description：使用cmd命令启动redis服务
     * @Author： ext.fengcheng
     * @Date：2023/11/10 18:09
     * @Param： []
     * @Return： void
     */
    public static void startRedisService() {
        try {
            // 启动redis命令（全路径命令）
            String commandPath = "D:\\gong-zuo\\kai-fa-gong-ju\\redis\\install\\redis-server.exe";
            Process process = Runtime.getRuntime().exec(commandPath);
            // 读取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 关闭流
            reader.close();
            // 等待命令执行完成
            int exitCode = process.waitFor();
            System.out.println("命令执行完成，退出码：" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            // 启动redis命令
            String commandPath = "D:\\gong-zuo\\kai-fa-gong-ju\\redis\\install\\redis-server.exe";
            // 停止redis命令
            // String commandPath = "D:\gong-zuo\kai-fa-gong-ju\redis\install\redis-cli shutdown";
            Process process = Runtime.getRuntime().exec(commandPath);

            // 读取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 关闭流
            reader.close();
            // 等待命令执行完成
            int exitCode = process.waitFor();
            System.out.println("命令执行完成，退出码：" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
